package com.lagou.edu.springbootcache.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.lagou.edu.springbootcache.dao.pojo.LagouWorkPo;
import com.lagou.edu.springbootcache.dao.repository.LagouWorkRepository;
import com.lagou.edu.springbootcache.service.CacheService;
import com.lagou.edu.springbootcache.vo.LagouWorkReqVo;
import com.lagou.edu.springbootcache.vo.LagouWorkRespVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import redis.clients.jedis.JedisCluster;

import java.sql.Timestamp;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Service
public class CacheServiceImpl implements CacheService {
    @Autowired
    private LagouWorkRepository repository;

    @Autowired
    private JedisCluster shareJedisCluster;

    //guava
    private LoadingCache<String, LagouWorkRespVo> loadingCache = CacheBuilder.newBuilder()
            .expireAfterWrite(20, TimeUnit.SECONDS)
            // 设置缓存上限
            .maximumSize(10)
            .build(new CacheLoader<String, LagouWorkRespVo>() {

                @Override
                public LagouWorkRespVo load(String key) {
                    return loadCache(key);
                }
            });

    @Override
    public void addCache(LagouWorkReqVo reqVo) {
        LagouWorkPo workPo = new LagouWorkPo();
        BeanUtils.copyProperties(reqVo, workPo);
        workPo.setCreateTime(new Timestamp(System.currentTimeMillis()));
        workPo.setUpdateTime(new Timestamp(System.currentTimeMillis()));
        repository.save(workPo);  //保存db
        LagouWorkRespVo respVo = new LagouWorkRespVo();
        BeanUtils.copyProperties(workPo, respVo);
        // 保存redis，20s过期
        String redisKey = "workKey:" + respVo.getId().toString();
        shareJedisCluster.set(redisKey, JSONObject.toJSONString(respVo));
        shareJedisCluster.expire(redisKey, 30);
    }

    @Override
    public LagouWorkRespVo getCache(String key) {
        try {
            Set<String> set = loadingCache.asMap().keySet();
            System.out.println(set.toString());
            return loadingCache.get(key);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private LagouWorkRespVo loadCache(String key) {
        System.out.println("本地缓存没有，从redis获取");
        LagouWorkRespVo respVo = new LagouWorkRespVo();
        String str = shareJedisCluster.get(key);
        if (StringUtils.isEmpty(str)) {
            System.out.println("redis没有，从db获取");
            LagouWorkPo workPo = repository.findById(Integer.parseInt(key)).get();
            if (Objects.nonNull(workPo)) { //存入redis
                BeanUtils.copyProperties(workPo, respVo);
                shareJedisCluster.set("workKey:" + key, JSONObject.toJSONString(respVo));
                shareJedisCluster.expire("workKey:" + key, 30);
            }
        } else {
            respVo = (LagouWorkRespVo) JSONObject.parse(str);
        }
        return respVo;

    }
}
